﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RuoVea.GoFastdfs.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuoVea.GoFastdfs.Common
{
    /// <summary>
    /// 获取文件列表工具类
    /// </summary>
    public class GetFileUtil
    {
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="showUrl"></param>
        /// <param name="serverAddress">服务地址</param>
        /// <param name="dir">要获取的目录(根目录为null)</param>
        /// <returns>List<FileResult></returns>
        public static List<FileResult> getDirOrFileList(String showUrl, String serverAddress, String dir)
        {
            JObject param = new JObject();
            if (!String.IsNullOrWhiteSpace(dir))
            {
                param.Add("dir", dir);
            }
            String result = HttpHelper.HttpPost(serverAddress + FinalAPI.API_LIST_DIR, param.ToJson());

            JObject parseObj = result.ToEntity<JObject>();

            List<FileResult> files = new List<FileResult>();
            if (parseObj.GetValue("message").ToString().Equals("") && !string.IsNullOrWhiteSpace(parseObj.GetValue("data").ToString()))
            {
                var parseArray = parseObj[("data")].ToList();
                for (int i = 0; i < parseArray.Count(); i++)
                {
                    FileResult fileResult = new FileResult();
                    var file = parseArray[(i)];
                    if (file[("name")].ToString().Equals("_big"))
                    {
                        continue;
                    }
                    fileResult.md5=file["md5"]?.ToString();
                    fileResult.path=file["path"]?.ToString();
                    fileResult.name=file["name"]?.ToString();
                    fileResult.is_dir=file["is_dir"].ToString().Equals("true");
                    fileResult.peerAddr=(showUrl);
                    if (fileResult.is_dir)
                    {
                        fileResult.size="0";
                    }
                    else
                    {
                        fileResult.size=(FileSizeUtil.GetLength((long)Convert.ToInt32((file["size"]?.ToString()))));
                    }
                    fileResult.mTime=(DateUtil.timeStamp2Date(file["mtime"]?.ToString(), null));
                    files.Add(fileResult);
                }
            }
            return files;
        }
    }
}
